const fs = require('fs');
const tinify = require('tinify');
const chalk = require('chalk');
const { promisify} = require('util');
const readFile = promisify(fs.readFile);
const {getImageFiles} = require('../utils')
const inquirer = require('inquirer');
function setKey(key) {
    tinify.key = key || 'MdcNxJs2pHBfs8BpMwrXc5qtxJghsxP2';
}
//tinypng的apiKey一个月最多只能压缩500张图片
async function validate(filePath,key) {
    console.log(chalk.green('正在认证tinyPng的key...'));
    setKey(key); //设置key
    return new Promise(resolve => {
        //tinyPng提供的回调方法，用于检测key是否通过验证
        tinify.validate(async (err) => {
            if(err){
                console.log(err);
                return resolve(false);
            }
            console.log(chalk.green('认证成功！'));
            const left = leftCount();
            console.log('getImageFiles(filePath)',getImageFiles(filePath));
            if(getImageFiles(filePath) > left){
                console.log(chalk.red('当前key的剩余可用数不足，请更换key重试！'));
                resolve(false);
            }
            if(left <= 0){
                console.log(chalk.red('当前key的剩余可用数已用尽，请更换key重试！'));
                resolve(false);
            }
            console.log(chalk.green(`当前key剩余可用数为 ${left}`));
            resolve(true);
        });
    });
};
//返回这个key对应已经压缩的图片数，一个月最多500张
function compressionCount() {
    return tinify.compressionCount;
};

//计算剩余可压缩的图片数目
function leftCount() {
    const total = 500;
    return total - Number(compressionCount());
};
//接收到压缩后的文件，然后写入文件替换
function writeFilePromise(file, content, cb) {
    return new Promise((resolve, reject) => {
        fs.writeFile(file, content, (err) => {
            if(err){
                return reject(err);
            }
            cb && cb();
            resolve();
        });
    });
};
//最主要的接口，调用tinify的api压缩图片然后返回
function toBufferPromise(sourceData) {
    return new Promise((resolve, reject) => {
        tinify.fromBuffer(sourceData).toBuffer((err, resultData) => {
            if (err) {
                return reject(err);
            }
            resolve(resultData);
        })
    });
};
 
async function imgMin(img) {
    try {
        console.log(chalk.blueBright(`开始压缩图片 ${img}`));
        const sourceData = await readFile(img);
        const resultData = await toBufferPromise(sourceData);
        await writeFilePromise(img, resultData, () => console.log(chalk.green(`图片压缩成功 ${img}`)));
    } catch (error) {
        console.log(error);
    }
};
 
module.exports = { validate, compressionCount, leftCount, imgMin };